package com.zhaowei.tlzy.allinpay.controller;

import com.zhaowei.tlzy.allinpay.service.AllInPayService;
import com.zhaowei.tlzy.allinpay.util.SybConstants;
import com.zhaowei.tlzy.allinpay.util.SybUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.TreeMap;

@RestController
@RequestMapping("/allInPay")
public class AllInPayController {
    @Autowired
    private AllInPayService allInPayService;


    @RequestMapping("/getScanPayCodeString")
    public String getScanPayCodeString(){

        return "";
    }

    @RequestMapping("/notifyurl")
    public String allInPayNotify(HttpServletRequest request, HttpServletResponse response)throws Exception{
        System.out.println("接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        TreeMap<String,String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        JSONObject jsonObject = new JSONObject(params);
        System.out.println("------------");
        System.out.println(jsonObject.toString());
        String s =jsonObject.get("rps").toString();
        JSONObject jsonObject1 = new JSONObject(s);
        System.out.println("------------");
        System.out.println(jsonObject1.toString());



//        try {
//            boolean isSign = SybUtil.validSign(params, SybConstants.SYB_APPKEY_TEST);// 接受到推送通知,首先验签
//            System.out.println("验签结果:"+isSign);
//            //验签完毕进行业务处理
//        } catch (Exception e) {//处理异常
//            // TODO: handle exception
//            e.printStackTrace();
//        }
//        finally{//收到通知,返回success
            response.getOutputStream().write("success".getBytes());
            response.flushBuffer();
//        }
        return "";
    }

    /**
     * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request){
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for(Object key:reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            //System.out.println(key+";"+value);
            map.put(key.toString(),value);
        }
        return map;
    }
}
